package com.naiterui.ehp.bs.agent.service.security.impl;

import java.io.IOException;
import java.util.Optional;

import com.naiterui.common.redis.RedisUtil;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bs.agent.entity.AgAgent;
import com.naiterui.ehp.bs.agent.exception.ExceptionCodes;
import com.naiterui.ehp.bs.agent.repository.IAgAgentRepository;
import com.naiterui.ehp.bs.agent.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.naiterui.ehp.bs.agent.service.security.ISecurityService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;

/**
 * @author yiren
 * @since 2022/2/9
 */
@Slf4j
@Service
public class AgentSecurityServiceImpl implements ISecurityService {
	@Autowired
	private IAgAgentRepository agAgentRepository;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveCheckToken(Long agentId, String token, HttpServletResponse response) throws IOException {
		if (agentId == null || StringUtils.isEmpty(token)){
			this.stuffErrorCode(response, ExceptionCodes.TOLOGIN);
			return false;
		}
		String loginCacheKey = RedisKeyUtil.getLoginTokenKey(agentId);
		try {
			String cacheToken = RedisUtil.valueOps().getString(loginCacheKey);
			if (token.equals(cacheToken)) {
				return true;
			}
		} catch (Exception e) {
			log.error("从redis中获取缓存用户登陆token失败,agentId=" + agentId, e);
		}

		AgAgent dbAgent = agAgentRepository.get(agentId);
		if (dbAgent == null) {
			// 提示去登陆
			this.stuffErrorCode(response, ExceptionCodes.TOLOGIN);
			return false;
		}

		if (AgAgent.ACCOUNT_STATUS_OFF == dbAgent.getAccountStatus()) {
			// 提示用户未注册
			this.stuffErrorCode(response, ExceptionCodes.AGENT_ACCOUNT_OFF);
			return false;
		}
		if (AgAgent.STATUS_LEAVE == dbAgent.getStatus()) {
			// 提示用户未注册
			this.stuffErrorCode(response, ExceptionCodes.AGENT_LEAVE);
			return false;
		}
		if (!token.equals(dbAgent.getToken())) {
			// 提示去登陆
			this.stuffErrorCode(response, ExceptionCodes.TOLOGIN);
			return false;
		}

		try {
			RedisUtil.valueOps().set(loginCacheKey, token);
		} catch (Exception e) {
			log.error("向redis中缓存用户登陆token失败,agentId=" + agentId, e);
		}

        return true;
	}
	private void stuffErrorCode(HttpServletResponse response, int errorCode) throws IOException {
		if (null == response) {
			return;
		}
		response.getWriter().println(JsonMapper.toJson(PublicService.returnResponseVO(errorCode)));
	}
}
